﻿using System.Net;
using System.Text;

namespace AuSys.Utils.StringUtils
{
    public static class KvPairsString
    {
        public const char equal = '=';
        public const char and = '&';

        /// <summary>
        /// 将“&amp;”分隔、“Key=Value”形式的字符串UrlDecode并解析为Dictionary
        /// </summary>
        /// <param name="queryString">UrlEncoded字符串</param>
        /// <returns>解析得到的字典</returns>
        public static Dictionary<string, string> ToDictionary(string queryString)
        {
            queryString = WebUtility.UrlDecode(queryString);
            var kvPairs = new Dictionary<string, string>();
            var parts = queryString.Split(and);
            foreach (var part in parts)
            {
                if (part.Length == 0)
                    continue;
                var kvPair = part.Split(equal);
                if (kvPair.Length == 2)
                {
                    var key = kvPair[0];
                    var value = kvPair[1];
                    kvPairs.TryAdd(key, value);
                }
            }
            return kvPairs;
        }
        /// <summary>
        /// 将Dictionary转换为“&amp;”分隔、“Key=Value”形式的字符串并UrlEncode
        /// </summary>
        /// <param name="dict">目标字典</param>
        /// <returns>UrlEncoded字符串</returns>
        public static string FromDictionary(Dictionary<string, string> dict)
        {
            StringBuilder sb = new();
            bool firstWritten = false;
            foreach(var kv in dict)
            {
                if (firstWritten)
                    sb.Append(and);
                else
                    firstWritten = true;
                sb.Append(kv.Key);
                sb.Append(equal);
                sb.Append(kv.Value);
            }
            return WebUtility.UrlEncode(sb.ToString());
        }
    }
}
